package com.zho.util.rctrl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class RemoteClient {
	private Socket socket;
	private PrintWriter writer;
	private BufferedReader reader;
	private BufferedReader in;
	boolean stop = false;
	private String host = null;
	private String port = null;

	public RemoteClient(String host, String port) {
		this.host = host;
		this.port = port;
	}

	public void run() {
		String inputLine = null;

		try {
			socket = new Socket(host, Integer.parseInt(port));
			writer = new PrintWriter(socket.getOutputStream(), true);
			reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));

			in = new BufferedReader(new InputStreamReader(System.in));

			String res = null;
			String cmd = null;

			while (!stop) {
				res = waitForResponce(reader);
				System.out.print(res);
				//cmd = in.readLine();
				cmd = "shutdown\nquit";
				if (cmd == null)
					break;
				writer.println(cmd);
				writer.flush();
			}

			writer.println("Quit");
			writer.flush();
			writer.close();
			reader.close();
			socket.close();

		} catch (UnknownHostException ue) {
			ue.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	private String waitForResponce(BufferedReader br) {
		char[] ary = new char[1024];
		int idx = 0;
		int ch = 0;
		String res = null;

		while (!stop) {
			try {
				ch = reader.read();
				ary[idx] = (char) ch;
				if (ch != -1)
					idx++;
				else
					stop = true;
			} catch (Exception e) {
				stop = true;
				System.err.println("" + e);
			}

			res = new String(ary, 0, idx);

			if (res.indexOf(">") != -1)
				return res;

			if (idx >= (ary.length - 1)) {
				stop = true;
				return res;
			}
		}
		return res;
	}

	public static void main(String args[]) {
		if (args.length != 2) {
			System.err
					.println("java com.f..rctrl.RemoteClient hostname port[Enter]");
			System.err.println("or");
			System.err
					.println("cat FILE|java com.f..rctrl.RemoteClient hostname port[Enter]");
			System.exit(3);
		}
		RemoteClient cl = new RemoteClient(args[0], args[1]);
		cl.run();
	}
}

// End of FILE.
